<template>
	<div>
		<ProTable ref="proTable" title="商品列表" :columns="activeTag == '4' ? columns1 : columns" :request-api="getTableList" :init-param="initParam">
			<template #searchHeader>
				<div class="mb16">
					<el-button type="primary" v-auth="'product:create:invoke'" @click="toAddGood"> 新增商品 </el-button>
				</div>
			</template>
			<!-- 表单 头部 数据 -->
			<template #tableHeader>
				<el-tabs v-model="activeTag" class="demo-tabs" @tab-click="handleTab">
					<el-tab-pane v-for="item in tags" :key="item.name" :label="`${item.label}(${item.data})`" :name="item.name"></el-tab-pane>
				</el-tabs>
			</template>
			<!-- Expand -->
			<template #expand="scope">
				{{ scope.row }}
			</template>

			<!-- 表格操作 -->
			<template #operation="{ row }">
				<el-button type="primary" v-auth="'product:details:invoke'" link :loading="previewLoading" @click="onPreview(row)"> 预览 </el-button>
				<el-divider direction="vertical" v-auth="'product:details:invoke'" />
				<el-button type="primary" v-auth="'product:link:invoke'" link @click="onLink(row)"> 链接 </el-button>
				<el-divider direction="vertical" v-auth="'product:link:invoke'" />
				<el-button type="primary" link v-if="['2', '3'].includes(activeTag)" v-auth="'product:audit:invoke'" @click="onAudit(row)"> 审核 </el-button>
				<el-divider direction="vertical" v-if="['2', '3'].includes(activeTag)" v-auth="'product:audit:invoke'" />
				<el-button
					type="primary"
					link
					v-auth-all="['product:edit:invoke', 'product:details:invoke']"
					@click="$router.push({ path: `/goods/list/edit/${row.id}` })"
				>
					编辑
				</el-button>
				<el-divider direction="vertical" v-auth-all="['product:edit:invoke', 'product:details:invoke']" />
				<el-button
					type="primary"
					v-auth-all="['product:create:invoke', 'product:details:invoke']"
					link
					@click="$router.push({ path: `/goods/list/add`, query: { id: row.id } })"
				>
					复制
				</el-button>
				<el-divider direction="vertical" v-auth-all="['product:create:invoke', 'product:details:invoke']" />
				<el-button type="primary" v-auth="'product:status:edit:invoke'" link v-if="activeTag === '1'" @click="changeStatus(row.id, true)">
					上架
				</el-button>
				<el-button type="primary" v-auth="'product:status:edit:invoke'" link v-else @click="changeStatus(row.id, false)"> 下架 </el-button>
				<el-divider direction="vertical" v-auth-all="['product:create:invoke', 'product:details:invoke']" />
				<el-button type="primary" v-auth="'product:delete:invoke'" link @click="onDelete(row.id)"> 删除 </el-button>
			</template>
		</ProTable>
		<Audit :visible="auditVisible" :row="auditRow" @handleClose="closeAudit"></Audit>
		<Link :visible="linkVisible" :row="linkRow" @handleClose="closeLink"> </Link>
	</div>
</template>

<script setup lang="tsx" name="goodsList">
import { onMounted, ref, reactive, computed, nextTick, onBeforeMount } from 'vue';
import dayjs from 'dayjs';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { NextLoading } from '/@/utils/loading';
import ProTable from '../../../../components/ProTable/index.vue';
import { ProTableInstance, ColumnProps } from '../../../../components/ProTable/interface';
import { fetchGoodsStatics, fetchGoodList, fetchTypeList, fetchDelGood, fetchGoodStatus, fetchGoodAduit, fetchQrCode } from '/@/api/goods';
import Audit from './dialog/audit.vue';
import Link from './dialog/link.vue';
import { fenToYuan } from '/@/utils/commonFunction';

const previewLoading = ref(false);

// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTable = ref<ProTableInstance>();

const router = useRouter();
const route = useRoute();

// 如果表格需要初始化请求参数，直接定义传给 ProTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({
	paramCode: 'id',
});

const activeTag = ref<any>('0');
const tags = ref<any>([
	{
		label: '销售中',
		name: '0',
		data: 0,
	},
	{
		label: '仓库中',
		name: '1',
		data: 0,
	},
	{
		label: '待业务审核',
		name: '2',
		data: 0,
	},
	{
		label: '待财务审核',
		name: '3',
		data: 0,
	},
	{
		label: '审核未通过',
		name: '4',
		data: 0,
	},
]);

const handleTab = () => {
	nextTick(() => {
		proTable.value?.getTableList();
	});
};

// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
// 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getTableList"
const getTableList = (params: any) => {
	let data = {
		...params,
		status: activeTag.value,
	};
	if (data.paramValue) {
		data[data.paramCode] = data.paramValue;
	}
	delete data.paramValue;
	delete data.paramCode;

	initStatics(data);
	return fetchGoodList(data);
};

// 表格配置项
const columns: ColumnProps<any>[] = [
	{
		prop: 'paramValue',
		label: '商品搜索',
		isShow: false,
		search: {
			span: 2,
			xs: 1,
			sm: 1,
			md: 2,
			lg: 1,
			xl: 1,
			render: (scope: any) => {
				const slot = {
					prepend: () => (
						<el-select
							v-model={scope.searchParam.paramCode}
							placeholder="Select"
							style="width: 100px"
							onChange={(value) => (scope.searchParam.paramCode = value)}
						>
							{searchArr.map((item) => (
								<el-option key={item.value} label={item.label} value={item.value} />
							))}
						</el-select>
					),
				};
				return <el-input v-model={scope.modelValue} v-slots={slot} placeholder={getPlaceholder.value} maxlength={50}></el-input>;
			},
		},
	},
	{
		prop: 'id',
		label: '商品ID',
		minWidth: 120,
	},
	{
		prop: 'productName',
		label: '商品名称',
		minWidth: 160,
		render: (scope) => {
			return (
				<div class="flex-center">
					<el-image class="flex-shrink" src={scope.row.productImage.split(',')[0]} style="width:50px;height:50px"></el-image>
					<div class="ml10" style="text-align:left">
						<div>{scope.row.productName}</div>
						<div>{scope.row.productCode}</div>
					</div>
				</div>
			);
		},
	},
	{
		prop: 'type',
		label: '商品类型',
		minWidth: 120,
		search: { el: 'select', props: { placeholder: '请选择商品类型', clearable: true, filterable: true } },
		enum: [
			{
				label: '实物',
				value: 0,
			},
			{
				label: '酒藏',
				value: 1,
			},
		],
		render(scope) {
			return scope.row.productType === 0 ? '实物' : '酒藏';
		},
	},
	{
		prop: 'productTypeId',
		label: '商品分类',
		minWidth: 120,
		search: { el: 'select', props: { placeholder: '请选择商品分类', clearable: true, filterable: true } },
		fieldNames: { label: 'name', value: 'id' },
		enum: () => {
			return new Promise<any>((resolve) => {
				fetchTypeList({ page: 1, size: 2000 }).then((res: any) => {
					resolve({
						code: 200,
						msg: 'success',
						data: res.data.records,
					});
				});
			});
		},
		render(scope) {
			return scope.row.productTypeName;
		},
	},
	{
		prop: 'status',
		label: '商品状态',
		minWidth: 120,
		render(scope: any) {
			return (
				tags.value.find((item: any) => {
					return item.name == scope.row.status;
				})?.label || ''
			);
		},
	},
	{
		prop: 'recommended',
		label: '是否推荐',
		minWidth: 120,
		render: (scope) => {
			return scope.row.recommended === 1 ? '是' : '否';
		},
	},
	{
		prop: 'price',
		label: '价格',
		minWidth: 120,
		render: (scope) => {
			const price = scope.row.price?.split('-');
			if (!price) {
				return '--';
			}
			return `${fenToYuan(price[0])}${price[1] ? `-${fenToYuan(price[1])}` : ''}`;
		},
	},
	{
		prop: 'availableInventory',
		label: '可售库存',
		minWidth: 120,
	},
	{
		prop: 'order',
		label: '排序',
		minWidth: 120,
	},
	{ prop: 'operation', label: '操作', fixed: 'right', width: 380, align: 'left' },
];
const columns1: ColumnProps<any>[] = [
	{
		prop: 'paramValue',
		label: '商品搜索',
		isShow: false,
		search: {
			span: 2,
			xs: 1,
			sm: 1,
			md: 2,
			lg: 1,
			xl: 1,
			render: (scope: any) => {
				const slot = {
					prepend: () => (
						<el-select
							v-model={scope.searchParam.paramCode}
							placeholder="Select"
							style="width: 100px"
							onChange={(value) => (scope.searchParam.paramCode = value)}
						>
							{searchArr.map((item) => (
								<el-option key={item.value} label={item.label} value={item.value} />
							))}
						</el-select>
					),
				};
				return <el-input v-model={scope.modelValue} v-slots={slot} placeholder={getPlaceholder.value} maxlength={50}></el-input>;
			},
		},
	},
	{
		prop: 'id',
		label: '商品ID',
		minWidth: 120,
	},
	{
		prop: 'name',
		label: '商品名称',
		minWidth: 160,
		render: (scope) => {
			return (
				<div class="flex-center">
					<el-image class="flex-shrink" src={scope.row.productImage.split(',')[0]} style="width:50px;height:50px"></el-image>
					<div class="ml10" style="text-align:left">
						<div class="ellipsis2">{scope.row.productName}</div>
						<div>物料编码：{scope.row.materialCode}</div>
					</div>
				</div>
			);
		},
	},
	{
		prop: 'type',
		label: '商品类型',
		minWidth: 120,
		search: { el: 'select', props: { placeholder: '请选择商品类型', clearable: true, filterable: true } },
		enum: [
			{
				label: '实物',
				value: 0,
			},
			{
				label: '酒藏',
				value: 1,
			},
		],
		render(scope) {
			return scope.row.productType === 0 ? '实物' : '酒藏';
		},
	},
	{
		prop: 'productTypeId',
		label: '商品分类',
		minWidth: 120,
		search: { el: 'select', props: { placeholder: '请选择商品分类', clearable: true, filterable: true } },
		fieldNames: { label: 'name', value: 'id' },
		enum: () => {
			return new Promise<any>((resolve) => {
				fetchTypeList({ page: 1, size: 2000 }).then((res: any) => {
					resolve({
						code: 200,
						msg: 'success',
						data: res.data.records,
					});
				});
			});
		},
		render(scope) {
			return scope.row.productTypeName;
		},
	},
	{
		prop: 'status',
		label: '商品状态',
		minWidth: 120,
		render(scope: any) {
			return (
				tags.value.find((item: any) => {
					return item.name == scope.row.status;
				})?.label || ''
			);
		},
	},
	{
		prop: 'recommended',
		label: '是否推荐',
		minWidth: 120,
		render: (scope) => {
			return scope.row.recommended === 1 ? '是' : '否';
		},
	},
	{
		prop: 'price',
		label: '价格',
		minWidth: 120,
		render: (scope) => {
			const price = scope.row.price?.split('-');
			if (!price) {
				return '--';
			}
			return `${fenToYuan(price[0])}${price[1] ? `-${fenToYuan(price[1])}` : ''}`;
		},
	},
	{
		prop: 'inventory',
		label: '库存',
		minWidth: 120,
	},
	{
		prop: 'order',
		label: '排序',
		minWidth: 120,
	},
	{
		prop: 'name',
		label: '未通过原因',
		minWidth: 120,
		render: (scope: any) => {
			return (
				<el-button type="danger" link>
					{scope.row.reason}
				</el-button>
			);
		},
	},
	{ prop: 'operation', label: '操作', fixed: 'right', width: 380, align: 'left' },
];

const searchArr = [
	{
		label: '商品ID',
		value: 'id',
	},
	{
		label: '物料编码',
		value: 'materialCode',
	},
	{
		label: '商品名称',
		value: 'name',
	},
];

const getPlaceholder = computed(() => {
	const target = searchArr.find((item) => {
		return item.value == proTable.value?.searchParam.paramCode;
	});
	return target ? `输入${target?.label}搜索` : '';
});

const auditVisible = ref(false);
const auditRow = ref();

const linkVisible = ref(false);
const linkRow = ref();

const initStatics = async (params: any) => {
	const { code, data } = await fetchGoodsStatics(params);
	if (code == 200) {
		tags.value = [
			{
				label: '销售中',
				name: '0',
				data: data.selling,
			},
			{
				label: '仓库中',
				name: '1',
				data: data.storage,
			},
			{
				label: '待业务审核',
				name: '2',
				data: data.businessCheck,
			},
			{
				label: '待财务审核',
				name: '3',
				data: data.financeCheck,
			},
			{
				label: '审核未通过',
				name: '4',
				data: data.checkFailed,
			},
		];
	}
};

const toAddGood = () => {
	router.push('/goods/list/add');
};

const onPreview = async (row: any) => {
	previewLoading.value = true;
	const { data } = await fetchQrCode({ id: row.id });
	previewLoading.value = false;
	ElMessageBox.alert(
		`<div class='flex-center'  style='text-align: center;'>
			<div>
				<image style='width:250px;height:250px' src="data:image/png;base64,${data.alipay}"></image>
				<div class='text-regular'>请使用支付宝扫码预览</div>
			</div>
			<div class='ml30'>
				<image style='width:250px;height:250px'  src="data:image/png;base64,${data.wechat}"></image>
				<div class='text-regular'>请使用微信扫码预览</div>
			</div>
		</div>`,
		'预览',
		{
			customStyle: { minWidth: '560px' },
			dangerouslyUseHTMLString: true,
			showConfirmButton: false,
		}
	);
};

const onLink = (row: any) => {
	linkVisible.value = true;
	linkRow.value = row;
};

const closeLink = () => {
	linkRow.value = null;
	linkVisible.value = false;
};

const onDelete = (id: any) => {
	ElMessageBox.confirm('确认删除该商品？', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	}).then(async () => {
		const res = await fetchDelGood({ id });
		if (res.code == 200) {
			ElMessage.success('删除成功');
			proTable.value?.getTableList();
		}
	});
};

const changeStatus = (id: any, bool: boolean) => {
	ElMessageBox.confirm(bool ? '确认上架？' : '确认下架？', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	}).then(async () => {
		const res = await fetchGoodStatus({ id });
		if (res.code == 200) {
			ElMessage.success(bool ? '上架成功' : '下架成功');
			proTable.value?.getTableList();
		}
	});
};

const onAudit = (row: any) => {
	auditRow.value = row;
	auditVisible.value = true;
};

const closeAudit = (success: boolean) => {
	auditVisible.value = false;
	if (success) {
		proTable.value?.getTableList();
	}
};

onBeforeMount(() => {
	activeTag.value = route.query.status || '0';
});
</script>

<style lang="scss">
.demo-tabs {
	.el-tabs__header {
		margin-bottom: 0;
	}
}
</style>
